import { Agent, IBoot } from 'egg';

const type = '[agent]';

export default class AgentBoot implements IBoot {
  private readonly agent: Agent;

  constructor(agent: Agent) {
    this.agent = agent;

    // 订阅 consul_register 事件
    agent.messenger.on('consul_register', async (by) => {
      agent.logger.info(type, 'start consul register by', by);

      try {
        await this.agent.m7Consul.registerToConsul();
        this.agent.logger.info(type, 'consul 注册成功');
      } catch (e) {
        this.agent.logger.error(type, 'consul 注册失败', e);
      }
    });

    // 订阅 consul_deregister 事件
    agent.messenger.on('consul_deregister', async (by) => {
      agent.logger.info(type, 'start consul deregister by', by);

      try {
        await this.agent.m7Consul.deregisterFromConsul();
        this.agent.logger.info(type, 'consul 取消注册成功');
      } catch (e) {
        this.agent.logger.error(type, 'consul 取消注册失败', e);
      }
    });
  }

  configWillLoad() {
    // Ready to call configDidLoad,
    // Config, plugin files are referred,
    // this is the last chance to modify the config.
  }

  configDidLoad() {
    // Config, plugin files have loaded.
  }

  async didLoad() {
    // All files have loaded, start plugin here.
  }

  async willReady() {
    // All plugins have started, can do some thing before agent ready.
  }

  async didReady() {
    // Worker is ready, can do some things
    // don't need to block the agent boot.
  }

  async serverDidReady() {
    // Server is listening.
    this.agent.logger.info(type, '服务启动成功，监听端口', this.agent.config.m7Consul.service.port);
    // 注册consul
    if (!this.agent.m7Consul.isRegistered) {
      try {
        await this.agent.m7Consul.registerToConsul();
        this.agent.logger.info(type, 'consul 注册成功');
      } catch (e) {
        this.agent.logger.error(type, 'consul 注册失败', e);
      }
    }
  }

  async beforeClose() {
    // Do some thing before agent close.
    // TODO 目前测试在本地开发时，npm run dev，直接控制台 ctrl + c 和c trl + \ 退出都不会触发beforeClose
    // kill masterPid 会触发，eggjs目前有个issue，增加一系列关闭事件，等待后续更新
    // https://github.com/eggjs/egg/issues/3179
    if (this.agent.m7Consul.isRegistered) {
      try {
        await this.agent.m7Consul.deregisterFromConsul();
        this.agent.logger.info(type, 'consul 取消注册成功');
      } catch (e) {
        this.agent.logger.error(type, 'consul 取消注册失败', e);
      }
    }
  }
}
